<!--
 * @Description: 查找处理人回复
-->
<template>
  <a-popover
    v-model="visible"
    :trigger="trigger"
    :placement="placement"
  >
    <div slot="content">
      <a-input
        @pressEnter="focusName(1)"
        v-model="keyword"
        :placeholder="$i18n('collaboration.summary.label.search.js')"
        allowClear
      >
        <a-space slot="addonAfter">
          <a-icon type="caret-up" @click="focusName(-1)" />
          <a-icon type="caret-down" @click="focusName(1)" />
          <a-icon type="close-circle" @click="visible = false" />
        </a-space>
      </a-input>
    </div>
    <slot :click="handleClick"></slot>
  </a-popover>
</template>

<script>
  // 查找人名元素的class
  const NAME_CLASS = 'author-name';
  // 命中之后添加的id
  const FOCUS_ID = 'name-focus';

  export default {
    name: 'CommentSearch',
    props: {
      trigger: {
        type: String,
        default: 'hover',
      },
      placement: {
        type: String,
        default: 'bottom',
      },
    },
    data() {
      return {
        visible: false,
        keyword: '', // 搜素关键词
        index: 0, // 当前高亮项目
        nodeList: [], // 缓存当前匹配的数组
      };
    },
    watch: {
      // 重新输入关键词，就从头开始
      keyword() {
        this.index = 0;
        this.resetNodeList();
      },
    },
    created() {
      this.$root.$on('commentUpdate', this.resetNodeList);
    },
    beforeDestroy() {
      this.$root.$off('commentUpdate', this.resetNodeList);
    },
    methods: {
      // 重置缓存列表
      resetNodeList() {
        this.nodeList = [];
      },
      /**
       * @description: 聚焦元素
       * @param {Number} offsetIndex 索引变换
       * @return {*}
       */
      focusName(offsetIndex) {
        if (!this.keyword) return;

        // 如果没有缓存就重新获取
        if (!this.nodeList.length) {
          let nodeListOf = document.querySelectorAll(`.${NAME_CLASS}`);
          for (let i = 0; i < nodeListOf.length; i++) {
            let dom = nodeListOf[i];
            this.nodeList.push(dom)
          }
          this.nodeList = this.nodeList.filter(dom => dom.textContent.includes(this.keyword));

          // 没有匹配元素直接不执行
          if (!this.nodeList.length) return;
        } else {
          // 不是第一次进来就变更索引（第一次进来就是0）
          let index = this.index + offsetIndex;
          const length = this.nodeList.length;

          if (index < 0) index = length - 1;

          if (index === length) index = 0;

          this.index = index;
        }

        const prev = document.querySelector(`#${FOCUS_ID}`);

        if (prev) prev.id = ''; // 清除上一次的结果

        // 添加这一次
        const current = this.nodeList[this.index];
        current.id = FOCUS_ID;
        current.scrollIntoView({ behavior: 'smooth', block: 'center' });
      },
      handleClick() {
        this.visible = true;
      },
    },
  };
</script>

<style scoped lang="scss">
  .icon {
    margin-right: 5px;
  }
</style>
